package de.uni_potsdam.hpi.bpt.ai.example;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONException;

import de.uni_potsdam.hpi.bpt.ai.collection.Model;
import de.uni_potsdam.hpi.bpt.ai.diagram.Diagram;
import de.uni_potsdam.hpi.bpt.ai.diagram.Shape;

public class StatisticsMuehlen extends Experiment{
	
	protected Map<String, Integer> data;
	
	public StatisticsMuehlen() {
		this.data = new HashMap<String, Integer>();
	}
	

	@Override
	protected void examineModel(Model model, Diagram diagram, int index) {
		Set<String> registered = new HashSet<String>();
		for (Shape shape : diagram.getShapes()) {
			String sid = shape.getStencil().getName();
			if (null == sid) {
				sid = "(null)" + shape.getStencilId();
			}
			
			if (!this.data.containsKey(sid)) {
				this.data.put(sid, 1);
				registered.add(sid);
			}
			else {
				if (!registered.contains(sid)) {	
					this.data.put(sid, this.data.get(sid) + 1);
					registered.add(sid);
				}
			}
		}
	}
	
	protected void printResults(String name, Integer count) {
		final Map<String, Integer> finalData = new HashMap<String, Integer>(data);
		Comparator<String> compare = new Comparator<String>() {
			public int compare(String o1, String o2) {
				return -1 * finalData.get(o1).compareTo(finalData.get(o2));
			}
		};
		
		List<String> keyset = new ArrayList<String>(finalData.keySet());
		Collections.sort(keyset, compare);
		
		System.out.println(String.format("%45s + %5d", name, count).replace(" ", "-"));
		for (String key: keyset) {
			System.out.println(String.format("%45s | %5d", key, finalData.get(key)));
		}		
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException, JSONException, IOException {
		StatisticsMuehlen sm;
		int c;
		
		sm = new StatisticsMuehlen();
		c = sm.eachModel(new HashSet<String>(Arrays.asList(new String[]{NS_EPC})));
		sm.printResults("EPC",c );
		
		System.out.println();
		
		sm = new StatisticsMuehlen();
		c = sm.eachModel(new HashSet<String>(Arrays.asList(new String[]{NS_BPMN})));
		sm.printResults("BPMN",c );
		
		
	}
}
